package StudyCode.summary.zipfile;

import java.io.*;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WritingToBinaryStream {
	public static void main(String[] args) {
		Movie[] movies = getMovies();
		DataOutputStream out = openOutputStream("movies.dat");
		for (Movie m : movies)
			writeMovie(m, out);
		closeFile(out);
		System.out.println("写入二进制流成功");
	}

	private static Movie[] getMovies() {
		Movie[] movies = new Movie[3];
		movies[0] = new Movie("美丽人生", 1946, 14.95);
		movies[1] = new Movie("星球大战", 1977, 17.95);
		movies[2] = new Movie("星球大战 7", 2018, 17.95);
		return movies;
	}

	private static DataOutputStream openOutputStream(String name) {
		DataOutputStream out = null;
		try {
			File file = new File(name);
			out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
			return out;
		} catch (IOException e) {
			System.exit(0);
		}
		return out;
	}

	private static void writeMovie(Movie m, DataOutputStream out) {
		try {
			out.writeUTF(m.title);
			out.writeInt(m.year);
			out.writeDouble(m.price);
		} catch (IOException e) {
			System.exit(0);
		}
	}

	private static void closeFile(DataOutputStream out) {
		try {
			out.close();
		} catch (IOException e) {
			System.exit(0);
		}
	}

}

class Movie {
	public String title;
	public int year;
	public double price;

	public Movie(String title, int year, double price) {
		this.title = title;
		this.year = year;
		this.price = price;
	}
}
